package com.example.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Des {

	// 加密
	public static String encryptDES(String encryptString, String key, String iv)
			throws Exception {
		IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes());
		SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, skey, zeroIv);
		byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
		return new String(Base64.encodeBase64(encryptedData));
	}

	// 解密
	public static String decryptDES(String decryptString, String key, String iv)
			throws Exception {
		byte[] byteMi = Base64.decodeBase64(decryptString.getBytes());
		IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes());
		SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, skey, zeroIv);
		byte decryptedData[] = cipher.doFinal(byteMi);
		return new String(decryptedData);
	}
}